#!/bin/bash
set -e
build() {
  echo "====== start build $ENV ======"
  cd $TOP
  scons -c
  scons -j4
  for i in release debug ; do
    ENV=$i
    cp -r $TOP/flash_bin_creater/ $TOP/output/${ENV}_flash_bin_creater
    cp $TOP/rtthread.bin $TOP/output/${ENV}_flash_bin_creater/app.bin
    cp $TOP/scripts/${ENV}_config.bin $TOP/output/${ENV}_flash_bin_creater/config.bin
    cp $TOP/scripts/pcm.bin $TOP/output/${ENV}_flash_bin_creater/pcm.bin
    cd $TOP/output/${ENV}_flash_bin_creater/
    python pack.py .
    cd -
    cp $TOP/output/${ENV}_flash_bin_creater/flash_all.bin $TOP/output/${ENV}_flash_all.bin
  done
  echo "====== make ${ENV} bin done======"
}

TOP=$(cd $(dirname $0) && pwd)
DATE=$(date +%Y%m%d%H)
echo $DATE
sed -i -e "/UNI_CROW_VERSION/s/\$(BUILD_ID)/${BUILD_ID}/"  \
       -e "/UNI_CROW_VERSION/s/\$(DATE)/${DATE}/" applications/hal/inc/uni_iot.h

if [ -f "noise_reduction" ];then
    sed -i "/USER_RUN_DEMO/s/0/1/g"  user/inc/user_config.h
    sed -i "/USER_RUN_DEMO_SELECT/s/USER_DEMO_SMART_AC/USER_DEMO_NOISE_CTRL/g"  user/inc/user_config.h
    sed -i "/OPEN_ASR_EVENT_UCP/s/1/0/g" user/inc/user_config.h
    rm noise_reduction
fi
DEMO_RUN=$(sed -n '/#define[[:space:]]USER_RUN_DEMO[[:space:]]/p' user/inc/user_config.h | awk '{split($0, a);print a[3]}')
DEMO_NAME=$(sed -n '/#define[[:space:]]USER_RUN_DEMO_SELECT/p' user/inc/user_config.h | awk '{split($0, a);print a[3]}')
if [ "${DEMO_RUN}"x == "1"x ]; then
    echo $DEMO_NAME
    if [ "${DEMO_NAME}"x == "USER_DEMO_NOISE_CTRL"x ]; then
        echo "copy uni_pinmux_upt_gen.h"
        cp -raf user/src/examples/inc_noise-reduction/uni_pinmux_upt_gen.h  drivers/device/inc/
    fi
fi

rm -rf $TOP/output && mkdir -p $TOP/output
cd scripts && python res_build_tool.py manual && cd -
build
echo "====== build done ==> output/ ======"
